package com.yantong.service.impl;

import com.yantong.mapper.*;
import com.yantong.pojo.*;
import com.yantong.pojo.vo.ProductDataVo;
import com.yantong.service.CategoryService;
import com.yantong.service.MemberCartService;
import com.yantong.service.ProductDataService;
import com.yantong.utils.DateUtils;
import com.yantong.utils.PageUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ProductDataServiceImpl implements ProductDataService {
	private static final Logger logger = LoggerFactory.getLogger(ProductServiceImpl.class);

	@Autowired
	private ProductDataMapper productDataMapper;
	@Autowired
	private ProductDataSpecMapper specMapper;
	@Autowired
	private ProductDataSkuMapper skuMapper;
	@Autowired
	private ProductDataSpecItemMapper specItemMapper;
	@Autowired
	private ProductCentreMapper centreMapper;
	@Autowired
	private CategoryService categoryService;
	@Autowired
	private ProductCentreMapper pCentreMapper;
	@Autowired
	private StringRedisTemplate redisTemplate;
	@Autowired
	private MemberCartService memberCartService;

	/*private static final String CACHE_NAME_PROUDCT = "PRODUCTDATA_";
	private static final String CACHE_SKU_NAME_PRODUCT = "PRODUCT_DATA_SKU_";
	private static final String CACHE_NAME = "CENTRE_PRODUCT_DATA";
	private static final String CACHE_SKU_NAME = "CENTRE_DATA_SKU_";*/
	
	//用
	public PageUtils<ProductData> list(int offset, int limit, Product vo) {
		PageUtils<ProductData> pageUtils = new PageUtils<>();
		HashMap<String, Object> searchMap = new HashMap<>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if (vo.getStatus() != null) {
			searchMap.put("status", vo.getStatus());
		}
		if (vo.getPcate() != null) {
			searchMap.put("pcate", vo.getPcate());
		}
		if (vo.getCcate() != null) {
			searchMap.put("ccate", vo.getCcate());
		}
		if (vo.getSupplierId() != null) {
			searchMap.put("supplierId", vo.getSupplierId());
		}
		if (StringUtils.isNotBlank(vo.getTitle())) {
			searchMap.put("title", vo.getTitle());
		}
		if (vo.getUpStartTime() != null) {
			searchMap.put("upStartTime", sdf.format(vo.getUpStartTime()));
		}
		if (vo.getUpEndTime() != null) {
			searchMap.put("upEndTime", sdf.format(vo.getUpEndTime()));
		}
		int total = (int) productDataMapper.count(searchMap);
		if (total > 0) {
			pageUtils.setTotal(total);
			pageUtils.setRows(productDataMapper.list(searchMap, new RowBounds(offset, limit)));
		} else {
			pageUtils.setRows(new ArrayList<>());
		}
		return pageUtils;
	}


	/**
	 * 导出功能数据列表 用
	 *
	 * @param vo
	 * @return
	 */
	public List<ProductDataVo> getExprotProductlist(Product vo) {
		HashMap<String, Object> searchMap = new HashMap<>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if (vo.getStatus() != null) {
			searchMap.put("status", vo.getStatus());
		}
		if (vo.getPcate() != null) {
			searchMap.put("pcate", vo.getPcate());
		}
		if (vo.getCcate() != null) {
			searchMap.put("ccate", vo.getCcate());
		}
		if (vo.getSupplierId() != null) {
			searchMap.put("supplierId", vo.getSupplierId());
		}
		if (StringUtils.isNotBlank(vo.getTitle())) {
			searchMap.put("title", vo.getTitle());
		}
		if (vo.getUpStartTime() != null) {
			searchMap.put("upStartTime", sdf.format(vo.getUpStartTime()));
		}
		if (vo.getUpEndTime() != null) {
			searchMap.put("upEndTime", sdf.format(vo.getUpEndTime()));
		}
		return productDataMapper.getExprotProductlist(searchMap);
	}

	;

	/**
	 * 得到活动类目商品
	 *
	 * @return
	 */
	public PageUtils<ProductCentre> getProductByCate() {
		PageUtils<ProductCentre> pageUtils = new PageUtils<ProductCentre>();
		List<ProductCentre> pCentreList = pCentreMapper.getProductCentreBycate();
		if (pCentreList.size() > 0) {
			pageUtils.setRows(pCentreList);
		}
		return pageUtils;
	}

	;

	/**
	 * 保存 用
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public int save(ProductDataVo obj) {
		if (obj == null) {
			return 0;
		}
		HashMap<String, String> map = new HashMap<>();

		try {
			List<ProductDataSku> skuList = obj.getSkuList();
			if (CollectionUtils.isNotEmpty(skuList)) {
				Integer totalStock = 0;
				for (ProductDataSku sku : skuList) {
					totalStock += sku.getStock() == null ? 0 : sku.getStock();
				}
				obj.setTotal(totalStock);
			}
			// 保存商品
			//obj.setCostprice(obj.getMarketprice());
			if(obj.getPcate()!=null && obj.getIsList()==null) {
				Category category = categoryService.getByKey(obj.getPcate());
            	if(category!=null) {
            		//添加分类显示
            		obj.setIsList(category.getIsList());
            	}
			}
			productDataMapper.insertSelective(obj);
			Long productId = obj.getId();

			// 保存商品规格
			List<ProductDataSpec> specList = obj.getSpecList();
			if (CollectionUtils.isNotEmpty(specList)) {
				for (ProductDataSpec spec : specList) {
					spec.setProductId(productId);
					specMapper.insertSelective(spec);
					Long specId = spec.getId();

					List<ProductDataSpecItem> specItemList = spec.getSpecItemList();
					for (ProductDataSpecItem item : specItemList) {
						// 保存规格属性
						item.setSpecId(specId);
						specItemMapper.insertSelective(item);

						map.put(item.getSpecItemHiddenId(), String.valueOf(item.getId())); // 拿到sku关联id和主键id
					}
				}
			}

			// 保存sku
			if (skuList != null && skuList.size() > 0) {
				for (ProductDataSku sku : skuList) {
					sku.setProductId(productId);
					String specs = "";
					String specItemHiddenIdStr = sku.getSpecItemHiddenId();
					if (StringUtils.isNotBlank(specItemHiddenIdStr)) {
						String[] s = specItemHiddenIdStr.split("_");
						int i = 1;
						for (String str : s) {
							if (s.length == i)
								specs += map.get(str);
							else
								specs += map.get(str) + "_";
							i++;
						}
					}
					sku.setSpecs(specs);
					skuMapper.insertSelective(sku);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("保存商品出错，信息为：{}", e.getMessage());
			return -1;
		}
		return 1;
	}

	/**
	 * 保存商品基本信息
	 *
	 * @param product
	 * @return
	 * @author baolingyu
	 * @date 2018年10月25日-下午12:02:57
	 */
	public int saveBaseInfo(ProductData product) {
		return productDataMapper.insertSelective(product);
	}

	//用
	public ProductData getByKey(Long id) {
		if (id == null) {
			return null;
		}
		ProductData product = productDataMapper.selectByPrimaryKey(id);
		if (product.getPcate() != 0 && product.getPcate() != null) {
			List<Category> ccategoryList = categoryService.listCategorys(product.getPcate());
			product.setCcategoryList(ccategoryList);
		}
		return product;
	}

	/**
	 * 更新 用
	 */
	@Override
	//@CacheEvict(value = {CACHE_NAME_PROUDCT, CACHE_SKU_NAME_PRODUCT,CACHE_NAME,CACHE_SKU_NAME}, allEntries = true)
	@Transactional(rollbackFor = Exception.class)
	public int update(ProductDataVo obj) {
		if (obj == null) {
			return 0;
		}
		HashMap<String, String> map = new HashMap<>();
		try {
			List<ProductDataSku> skuList = obj.getSkuList();
			if (obj.getUpStartTime() != null) {
				//如果现在的时间小于上架开始时间才可以修改规格库存
				if (new Date().compareTo(obj.getUpStartTime()) == -1) {
					if (CollectionUtils.isNotEmpty(skuList)) {
						Integer totalStock = 0;
						for (ProductDataSku sku : skuList) {
							totalStock += sku.getStock() == null ? 0 : sku.getStock();
						}
						obj.setTotal(totalStock);
					}
				}
			}
			  if(obj.getPcate()!=null) {
	            	Category  category = categoryService.getByKey(obj.getPcate());
	            	if(category!=null) {
	            		//添加分类显示
	            		obj.setIsList(category.getIsList());
	            	}
	            }
			// 更新商户商品基本信息
			//ProductCentre pCentre = new ProductCentre();
			//packProduct(pCentre, obj);
			// 更新商品库基本信息(供货价和市场价相同)
			//obj.setCostprice(obj.getMarketprice());
			productDataMapper.updateByPrimaryKeySelective(obj);
		

			//pCentreMapper.updateProductCentre(pCentre);
			/*if (pCentre.getStatus() == 0) {
				HashMap<String,Object> req =new HashMap();
				req.put("productId",obj.getId());
				List<ProductCentre> listByWhere = pCentreMapper.getListByWhere(req);
				for (ProductCentre productCentre1 : listByWhere) {
					delCart(productCentre1.getId(),productCentre1.getIsKuaidi());
				}

			}*/
		/*	//判断时间是否
			if (obj.getUpStartTime() != null) {*/
				/*//如果现在的时间小于上架开始时间才可以修改规格
				if (new Date().compareTo(obj.getUpStartTime()) == -1) {*/
					// 更新商品规格,先删除，在新增
					List<ProductDataSpec> specList = obj.getSpecList();
					specMapper.deleteByProductId(obj.getId()); // 删除
					if (null != obj.getHasoption() && obj.getHasoption() == 1) {
						for (ProductDataSpec spec : specList) {
							spec.setProductId(obj.getId());
							specMapper.insertSelective(spec);
							Long specId = spec.getId();

							List<ProductDataSpecItem> specItemList = spec.getSpecItemList();
							for (ProductDataSpecItem item : specItemList) {
								// 保存规格属性
								item.setSpecId(specId);
								specItemMapper.insertSelective(item);

								map.put(item.getSpecItemHiddenId(), String.valueOf(item.getId())); // 拿到sku关联id和主键id
							}
						}
					}

					// 保存sku
					skuMapper.deleteByProductId(obj.getId());
					if (obj.getHasoption() != null && (obj.getHasoption().intValue() == 1) && CollectionUtils.isNotEmpty(skuList)) {
						for (ProductDataSku sku : skuList) {

							sku.setProductId(obj.getId());
							String specs = "";
							String specItemHiddenIdStr = sku.getSpecItemHiddenId();
							if (StringUtils.isNotBlank(specItemHiddenIdStr)) {
								String[] s = specItemHiddenIdStr.split("_");
								int i = 1;
								for (String str : s) {
									if (s.length == i) {
										specs += map.get(str);
										continue;
									}
									specs += map.get(str) + "_";
									i++;
								}
							}
							sku.setSpecs(specs);
							skuMapper.insertSelective(sku);
						}
					}
				/*}
			}*/
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("更新商品出错，信息为：{}", e.getMessage());
			return -1;
		}
		return 1;
	}

	/*public void packProduct(ProductCentre pCentre, ProductData obj) {
		ProductData product = productDataMapper.selectByPrimaryKey(obj.getId());
		pCentre.setProductId(obj.getId());
		pCentre.setTitle(obj.getTitle());
		pCentre.setShortTitle(obj.getShortTitle());
		pCentre.setGoodscode(obj.getGoodscode());
		pCentre.setPcate(obj.getPcate());
		pCentre.setCcate(obj.getCcate());
		pCentre.setSupplierId(obj.getSupplierId());
		pCentre.setUnit(obj.getUnit());
		pCentre.setSelfvalue(obj.getSelfvalue());
		pCentre.setTimestart(obj.getTimestart());
		pCentre.setTimeend(obj.getTimeend());
		pCentre.setThumb(obj.getThumb());
		pCentre.setThumbSquare(obj.getThumbSquare());
		pCentre.setThumbUrl(obj.getThumbUrl());
		pCentre.setVideourl(obj.getVideourl());
		pCentre.setProductprice(obj.getProductprice());
		pCentre.setCostprice(obj.getMarketprice());
		pCentre.setIsList(obj.getIsList());
		if(!product.getSuggestsaleprice().toString().equals(obj.getSuggestsaleprice().toString())) {
			pCentre.setMarketprice(obj.getSuggestsaleprice());
		}
		pCentre.setWeight(obj.getWeight());
		pCentre.setTotal(obj.getTotal());
		pCentre.setSales(obj.getSales());
		pCentre.setViewcount(obj.getViewcount());
		pCentre.setCredit(obj.getCredit());
		pCentre.setStatus(obj.getStatus());
		//如果将商品商品立即上架则将实际销售数量更新为0
		pCentre.setSalesready(0);
		pCentre.setUpStartTime(obj.getUpStartTime());
		pCentre.setUpEndTime(obj.getUpEndTime());
		pCentre.setIsgongyi(obj.getIsgongyi());
		pCentre.setShowsupply(obj.getShowsupply());
		pCentre.setUncancelable(obj.getUncancelable());
		pCentre.setDescription(obj.getDescription());
		pCentre.setHasoption(obj.getHasoption());
		pCentre.setHasoptionsbuy(obj.getHasoptionsbuy());
		pCentre.setAreas(obj.getAreas());
		pCentre.setTimestart(obj.getTimestart());
		pCentre.setTimeend(obj.getTimeend());
		pCentre.setDisplayorder(obj.getDisplayorder());
		pCentre.setIsrecommand(obj.getIsrecommand());
		pCentre.setIsnew(obj.getIsnew());
		pCentre.setIshot(obj.getIshot());
		pCentre.setIsdiscount(obj.getIsdiscount());
		pCentre.setIsmiaosha(obj.getIsmiaosha());
		pCentre.setIslimited(obj.getIslimited());
		pCentre.setIstime(obj.getIstime());
		pCentre.setIszhicai(obj.getIszhicai());
		pCentre.setIsmao(obj.getIsmao());
		pCentre.setIsfanchang(obj.getIsfanchang());
		pCentre.setIsfashi(obj.getIsfashi());
		pCentre.setIszhutihuakuang(obj.getIszhutihuakuang());
		pCentre.setIsbig(obj.getIsbig());
		pCentre.setSales(obj.getSales());
		pCentre.setMaxbuy(obj.getMaxbuy());
		pCentre.setUsermaxbuy(obj.getUsermaxbuy());
	}*/

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int btnUpdate(Long id, String column) {
		ProductData product = productDataMapper.selectByPrimaryKey(id);

		ProductCentre productCentre = new ProductCentre();
		productCentre.setProductId(product.getId());
		try {
			switch (column) {
				case "isnew":
					product.setIsnew(product.getIsnew() == 1 ? 0 : 1);
					productCentre.setIsnew(product.getIsnew());
					break;
				case "isTeamBuy":
					product.setIsTeamBuy(product.getIsTeamBuy() == 1 ? 0 : 1);
					productCentre.setIsTeamBuy(product.getIsTeamBuy());
					break;
				case "isbig":
					product.setIsbig(product.getIsbig() == 1 ? 0 : 1);
					productCentre.setIsbig(product.getIsbig());
					break;
				case "ishot":
					product.setIshot(product.getIshot() == 1 ? 0 : 1);
					productCentre.setIshot(product.getIshot());
					break;
				case "isrecommand":
					product.setIsrecommand(product.getIsrecommand() == 1 ? 0 : 1);
					productCentre.setIsrecommand(product.getIsrecommand());
					break;
				case "isdiscount":
					product.setIsdiscount(product.getIsdiscount() == 1 ? 0 : 1);
					productCentre.setIsdiscount(product.getIsdiscount());
					break;
				case "islimited":
					product.setIslimited(product.getIslimited() == 1 ? 0 : 1);
					productCentre.setIslimited(product.getIslimited());
					break;
				case "istime":
					product.setIstime(product.getIstime() == 1 ? 0 : 1);
					productCentre.setIstime(product.getIstime());
					break;
				case "ismiaosha":
					product.setIsmiaosha(product.getIsmiaosha() == 1 ? 0 : 1);
					productCentre.setIsmiaosha(product.getIsmiaosha());
					break;
				case "isvip":
					product.setIsvip(product.getIsvip() == 1 ? 0 : 1);
					productCentre.setIsvip(product.getIsvip());
					break;
				case "iszhicai":
					product.setIszhicai(product.getIszhicai() == 1 ? 0 : 1);
					productCentre.setIszhicai(product.getIszhicai());
					break;
				case "ismao":
					product.setIsmao(product.getIsmao() == 1 ? 0 : 1);
					productCentre.setIsmao(product.getIsmao());
					break;
				case "isfanchang":
					product.setIsfanchang(product.getIsfanchang() == 1 ? 0 : 1);
					productCentre.setIsfanchang(product.getIsfanchang());
					break;
				case "isgerida":
					product.setIsgerida(product.getIsgerida() == 1 ? 0 : 1);
				productCentre.setIsgerida(product.getIsgerida());
					break;
				case "isfashi":
					product.setIsfashi(product.getIsfashi() == 1 ? 0 : 1);
					productCentre.setIsfashi(product.getIsfashi());
					break;
				case "iszhutihuakuang":
					product.setIszhutihuakuang(product.getIszhutihuakuang() == 1 ? 0 : 1);
					productCentre.setIszhutihuakuang(product.getIszhutihuakuang());
					break;
				case "status":
					product.setStatus(product.getStatus() == 1 ? 0 : 1);
					productCentre.setStatus(product.getStatus());
					break;
			}
			centreMapper.updateProductCentre(productCentre);
			if (product.getStatus()==0){
				HashMap<String,Object> req =new HashMap();
				req.put("productId",product.getId());
				List<ProductCentre> listByWhere = pCentreMapper.getListByWhere(req);
				for (ProductCentre productCentre1 : listByWhere) {
					delCart(productCentre1.getId(),productCentre1.getIsKuaidi());
				}
			}
			return productDataMapper.updateByPrimaryKeySelective(product);

		} catch (Exception e) {
			logger.error("product btnUpdate is error, the message is {}", e.getMessage());
			return 0;
		}
	}

	/**
	 * 删除 用
	 */
	@Override 
	@Transactional(rollbackFor = Exception.class)
	public int remove(Long id) {
		if (id == null) {
			return 0;
		}

//		List<Long> productCentreIds = centreMapper.getRemoveProductId(id); // t_product_centre表需要删除
		ProductData obj = new ProductData();

		obj.setId(id);
		obj.setDeleted(0);
		try {
//			centreMapper.batchRemove(productCentreIds);
		//	centreMapper.removeByProductId(id);
			productDataMapper.updateByPrimaryKeySelective(obj);
		} catch (Exception e) {
			logger.info("t_product_base删除商品信息出错，{}", e.getMessage());
			return -1;
		}
		return 1;
	}

	/*@Override
	@Cacheable(value = CACHE_NAME_PROUDCT, keyGenerator = "localKeyGenerator")
	public ProductData getByKeyWithCache(Long id) {
		if (id == null) {
			return null;
		}
		return productDataMapper.selectByPrimaryKey(id);
	}*/

	@Override
	public int changeStock(int total, Product base) {
		return productDataMapper.changeStock(total, base.getId(), base.getVersion());
	}

	@Override
	public int changeStock(int total, Long productId) {
		return productDataMapper.changeStock(total, productId, null);
	}

	@Override
	public int refundStock(int total, Product base) {
		return productDataMapper.refundStock(total, base.getId(), base.getVersion());
	}

	@Override
	public List<ProductData> list(String idOrName) {
		HashMap<String, Object> map = new HashMap<>();
		map.put("idOrName", idOrName);
		int total = (int) productDataMapper.count(map);
		if (total > 0) {
			return productDataMapper.list(map);
		} else {
			return new ArrayList<>();
		}
	}

	/**
	 * 商品详情，带规格+属性+sku  用
	 * @param id
	 * @return
	 * @author baolingyu
	 * @date 2018年9月18日-下午4:04:41
	 */
	@Override
	public ProductDataVo detail(Long id) {
		ProductData product = productDataMapper.selectByPrimaryKey(id);
		ProductDataVo vo = new ProductDataVo();
		BeanUtils.copyProperties(product, vo);
		List<ProductDataSpec> specList = specMapper.selectByProductId(product.getId());
		// 获取规格+规格属性
		if (CollectionUtils.isNotEmpty(specList)) {
			for (ProductDataSpec spec : specList) {
				List<ProductDataSpecItem> specItemList = specItemMapper.selectBySpecId(spec.getId());
				spec.setSpecItemList(specItemList);
			}
			vo.setSpecList(specList);
		}

		// 获取sku
		List<ProductDataSku> skuList = skuMapper.selectByProductId(product.getId());
		vo.setSkuList(skuList);
		return vo;
	}

	@Override
	public PageUtils<ProductData> list(int offset, int limit, String idOrName) {
		PageUtils<ProductData> pageUtils = new PageUtils<>();
		HashMap<String, Object> searchMap = new HashMap<>();


		if (StringUtils.isNotBlank(idOrName)) {
			searchMap.put("idOrName", idOrName);
		}
		searchMap.put("inTime", "1");
		int total = (int) productDataMapper.count(searchMap);
		if (total > 0) {
			pageUtils.setTotal(total);
			pageUtils.setRows(productDataMapper.list(searchMap, new RowBounds(offset, limit)));
		} else {
			pageUtils.setRows(new ArrayList<>());
		}
		return pageUtils;
	}

	@Override
	public PageUtils<ProductData> listBaseProduct(int offset, int limit, String idOrName, String upStartTime, String upEndTime,Long pcate) {
		PageUtils<ProductData> pageUtils = new PageUtils<>();
		HashMap<String, Object> searchMap = new HashMap<>();

		if (StringUtils.isNotBlank(idOrName)) {
			searchMap.put("idOrName", idOrName);
		}
		if (StringUtils.isNotBlank(upStartTime)) {
			searchMap.put("upStartTime", upStartTime);
		}
		if (StringUtils.isNotBlank(upEndTime)) {
			searchMap.put("upEndTime", upEndTime);
		}
		if(pcate!=null) {
			searchMap.put("pcate", pcate);
		}
		int total = (int) productDataMapper.listBaseProductCount(searchMap);
		if (total > 0) {
			pageUtils.setTotal(total);
			pageUtils.setRows(productDataMapper.listBaseProduct(searchMap, new RowBounds(offset, limit)));
		} else {
			pageUtils.setRows(new ArrayList<>());
		}
		return pageUtils;
	}

	@Override
	public int changeBaseProductByIdMap(Map<Object, Object> updMap) {
		return productDataMapper.changeBaseProductByIdMap(updMap);
	}



	@Override
	public void autoUpdateCart() {
		HashMap<String, Object> req = new HashMap<>();
		req.put("status", 2);
		Date date = new Date();
		date.setTime(date.getTime() - 15 * 60 * 60 * 1000);
		req.put("upEndTime", date);
		List<ProductCentre> listByWhere = pCentreMapper.getListByWhere(req);
		if (CollectionUtils.isNotEmpty(listByWhere)){
			for (ProductCentre pCentre : listByWhere) {
					delCart(pCentre.getId(),pCentre.getIsKuaidi());
			}
		}


	}


	/**
	 * 清空购物车
	 * @param id
	 */
	@Override
	public void delCart(Long id,Integer isKuaidi ) {
		Set<Object> keys = redisTemplate.opsForHash().keys("CART_KEY:" + id);
		//List<Object> values = redisTemplate.opsForHash().values("CART_KEY:" + id);
		if (CollectionUtils.isNotEmpty(keys)) {
			for (Object key : keys) {
				String[] split = key.toString().split(",");
				String mid = split[0];
				String[] split1 = mid.split(":");
				memberCartService.removeItemRedis(Long.parseLong(split1[0]),Long.parseLong(split1[1]),split[1],isKuaidi);
				//redisTemplate.opsForHash().delete(split[0],split[1]);
			}
			redisTemplate.delete("CART_KEY:" + id);
		}

	}
	
	
	/**
	 * 复制单品 用
	 * @param productId
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public	int copyProduct(Long id) {
		//平台商品Id
//	      Long  productId = 	productDataMapper.getId()+1;
		//得到复制的商品
	      ProductData product = 	productDataMapper.getProduct(id);
		 //平台商品sku 
		  List<ProductDataSku> centreList  =  skuMapper.selectByProductId(id);
		  //平台商品spec  
		  List<ProductDataSpec> specList =  specMapper. getByProductId(id);
		/* String end = DateUtils.format(DateUtils.getAddDayDate(new Date(), +1), "yyyy-MM-dd") + " 20:00:00";
	     String start  = DateUtils.format(new Date(), "yyyy-MM-dd") + " 20:00:00";*/
		 //id清空
//	     product.setId(productId);
	    /* product.setUpStartTime(DateUtils.parseDate(start,"yyyy-MM-dd HH:mm:ss"));
	     product.setUpEndTime(DateUtils.parseDate(end,"yyyy-MM-dd HH:mm:ss"));*/
	     product.setTotal(null);
	     product.setCreatetime(new Date());
	     product.setSales(null);
	     product.setSalesreal(null);
	    /* product.setTimestart(DateUtils.parseDate(start,"yyyy-MM-dd HH:mm:ss"));
	     product.setTimeend(DateUtils.parseDate(end,"yyyy-MM-dd HH:mm:ss"));*/
	     product.setDeleted(1);
	     product.setGrandtotal(null);
	     product.setManudate(DateUtils.format(new Date(), "yyyy-MM-dd"));
		 //添加平台新商品
		int num =    productDataMapper.insertSelective(product);
		
	
		if(CollectionUtils.isNotEmpty(specList)) {
			Long specId = null; 
			//添加spec
			for (int i = 0; i < specList.size(); i++) {
				//specItem
				  List<ProductDataSpecItem> specItemList = specItemMapper.selectBySpecId( specList.get(i).getId());
				 ProductDataSpec spec = new ProductDataSpec();
				 spec = specList.get(i);
				spec.setProductId(product.getId());
				specId = specMapper.getMaxId()+(i+1);
			
				spec.setId(specId);
				//添加sku
				specMapper.insertSelective(spec);
				
				  if(CollectionUtils.isNotEmpty(specItemList)) {
					  ProductDataSpecItem productSpecItem = null;
					  for (int j = 0; j < specItemList.size(); j++) {
						  productSpecItem = specItemList.get(j);
						  productSpecItem.setId(null);
						  productSpecItem.setShow(null);
						  productSpecItem.setSpecId(specId);
						  //添加specItem
						  specItemMapper.insertSelective(productSpecItem);
					}
					 
				  }
			}
		}
		
		//得到平台productSpecItem
//		 List<ProductDataSpecItem> productSpecItemList = specItemMapper.selectByProductId (productId);
		if(CollectionUtils.isNotEmpty(centreList)) {
			ProductDataSku sku = null;
			//添加sku
			for (int i = 0; i < centreList.size(); i++) {
				 sku = centreList.get(i);
				 sku.setId(null);
				 sku.setStock(null);
				 sku.setSales(null);
				 sku.setSalesreal(null);
				 sku.setSalesready(null);
//				 sku.setSpecs(productSpecItemList.get(i).getId().toString());
				 sku.setProductId(product.getId());
				 //添加
				 skuMapper.insertSelective(sku);
			}
		}
		
		return num;
	};
	
}
